// 业务逻辑相关的工具
import store from '@/store'
import {GLOBAL_DICT, obsField} from '@/config/constant'
import {MessageBox} from 'element-ui'

/**
 * 获取下拉框选项
 * @param nameOrCode 下拉框的内容名称或 code
 */
export function globalNamedOptions(nameOrCode) {
  const key = parseInt(nameOrCode, 10)
  const codeKey = Number.isNaN(key) ? GLOBAL_DICT[nameOrCode] : key

  return store.state['globalSelectionOptions'][codeKey] || []
}

/**
 * 根据下拉框选项的 value 返回实际显示值
 * @param codeOrSelections 下拉框编码 或 下拉框名称 或 下拉框实际数据
 * @param value 选项的 value 值
 * @returns {*} 选项的文字内容
 */
export function optionDisplay(codeOrSelections, value) {
  if (Array.isArray(codeOrSelections)) {
    return (codeOrSelections.find(item => item.value === value) || {label: ''}).label
  }

  return (globalNamedOptions(codeOrSelections).find(item => Number(item.value) === Number(value)) || {label: ''}).label
}

/**
 * 根据节点的 code 获取节点路径
 * @param tree 待查找的树形结构
 * @param findCode 待查找的节点 code
 */
export function treeKeys(tree, findCode) {
  const pathArr = []
  let hasFound = false

  function _dfs(root) {
    if (root && root.code === findCode) {
      return hasFound = true
    }

    pathArr.push(root.code)
    for (let i = 0; root.childs && i < root.childs.length; i++) {
      if (_dfs(root.childs[i])) {
        break
      }
    }
    hasFound || pathArr.pop()

    return hasFound
  }

  _dfs(tree)
  return pathArr
}

/**
 * 根据节点 code 获取父节点的 code
 * @param tree 待查找的树形结构
 * @param findCode 要查找节点的 code
 */
export function treeParentCode(tree, findCode) {
  const res = treeKeys(tree, findCode)
  const parent = res.indexOf(findCode) - 1

  return (parent > -1) ? res[parent] : ''
}

/**
 * 过滤掉未授权的路由
 * @param routes
 * @param curRoleType 当前登录用户 角色 type
 */
export const handleFilterRoute = (routes, curRoleType) => {
  const _innerFilter = (arr) => {
    const res = arr.filter(item => !item.meta.roleType || (item.meta.roleType && item.meta.roleType.includes(parseInt(curRoleType, 10))))
    res.forEach((item, idx) => {
      if (Array.isArray(item.children)) {
        res[idx].children = _innerFilter(item.children)
      }
    })

    return res
  }

  return _innerFilter(JSON.parse(JSON.stringify(routes)))
}

/**
 * 建立 ws 消息推送通道
 * @param commit
 * @param dispatch
 * @param userId
 */
export function connectWSChannel({commit, dispatch}, userId) {
  if (!window['WebSocket']) {
    alert('当前浏览器不支持WebSocket')
  } else {
    const url = process.env.VUE_APP_BASE_API.replace('http', 'ws')
    if (userId !== undefined && userId !== null) {
      window._webSocket = new WebSocket(`${url}/websocket/web/${userId}`)

      window._webSocket.onopen = function (e) {
        console.log('创建了新连接')
      }

      window._webSocket.onerror = function (e) {
        console.log('遇到了错误')
        console.log(e)
      }

      window._webSocket.onclose = function (e) {
        console.log('关闭了连接')
        console.log(e)
      }

      window._webSocket.onmessage = function (e) {
        console.log('收到了消息')
        handleWSMessage({commit, dispatch}, JSON.parse(e.data))
      }
    }
  }

  window.onbeforeunload = function (e) {
    window._webSocket && window._webSocket.close()
    window._webSocket = undefined
  }
}

export function handleWSMessage({commit, dispatch}, payload) {
  switch (Number(payload.type)) {
    // 一般消息
    // 踢出
    case 1:
      MessageBox.alert(payload.message, '下线通知', {
        confirmButtonText: '确定',
        callback: action => {
          dispatch('user/logout')
        }
      })
      break
  }
}

/**
 * 处理年级-班级树形结构
 * 将根节点的 childs 数据替换为教师数据
 */
export function handleTreeData(tree) {
  if (!tree) {
    return -1
  }

  if (!tree.childs && tree.teacherVos) {
    tree.teacherVos.forEach(teacher => {
      teacher.pcode = tree.code
    })
    tree.childs = tree.teacherVos

    return -1
  }

  if (Array.isArray(tree.childs)) {
    tree.childs.forEach(child => {
      handleTreeData(child)
    })
  }
}

/**
 * 判断传入节点是否是班级节点
 * （判断班级节点的爷爷节点是否是校园节点）
 */
export function isClassNode(node) {
  const orgCode = store.getters['user/orgCode']
  // 判断拖拽节点是否是班级节点
  return node?.parent?.parent?.parent?.data[0]?.code === orgCode
}
